package cn.dhnep.demo.controller;

import cn.dhnep.demo.pojo.entity.Result;
import cn.dhnep.demo.service.ActivityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @Author 邱文彬
 * @Date 2021/12/6 10:02
 * @Version 1.0
 */


@RestController
@RequestMapping("/Activity")
public class ActivityController {

    //    设置上传文件的最大值
    public static final int AVATAR_MAX_SIZE = 10 * 1024 * 1024;
    //    设置上床文件的类型
    public static final List<String> AVATAR_TYPE = new ArrayList<>();

    static {
        AVATAR_TYPE.add("image/jpeg");
        AVATAR_TYPE.add("image/png");
        AVATAR_TYPE.add("image/bmg");
        AVATAR_TYPE.add("image/gif");

    }


    @Autowired
    private ActivityService activityService;

    @RequestMapping(value = "/insertActivity",method = RequestMethod.POST )
    public Result insertActivity(@RequestParam("file") MultipartFile file,
                                 @RequestParam("Activity") String Activity,
                                 @RequestParam("pictureName")String pictureName,
                                 @RequestParam("targetWeight") double targetWeight,
                                 HttpServletRequest request) throws IOException {

//        判断文件是否为空
        if (file.isEmpty()) {
            return new Result(10001, "未接收到图片", null);
        }
//        判断文件的大小是否超出限制
        if (file.getSize() > AVATAR_MAX_SIZE) {
            return new Result(10002, "文件大小超出上传最大值", null);
        }

//        判断文件的类型是否是规定的类型
        String contentType = file.getContentType();
//        如果集合包含某个元素则返回true
        if (!AVATAR_TYPE.contains(contentType)) {
            return new Result(10003, "文件类型不支持", null);
        }

//        设置将来要存放的目录

        File directory = new File(new File(ResourceUtils.getURL("").getPath()) + "/src/main/resources/static/Activity");


//        将一个File指向这个路径,判断是有该文件,如果没有则创建
        File dir = new File(directory.toString());
        //        判断是否存在,不存在则创建目录

        System.out.println(dir.toString());
        if (!dir.exists()) {
            dir.mkdirs();
            System.out.println("不存在,创建成功");
        }


        //        获取到这个文件的名称,UUID工具来将生成一个新的字符创作为文件名
        String originalFilename = file.getOriginalFilename();


        int index = originalFilename.lastIndexOf(".");


        String suffix = originalFilename.substring(index);

        String filename2 = UUID.randomUUID().toString().toUpperCase() + suffix;
        System.out.println(filename2);
        File dest = new File(dir, filename2); // 是一个空文件
//        将file的数据写入到这个空文件中

        try {
            file.transferTo(dest);
        } catch (IOException e) {
            return new Result(10004, "保存图片时发生异常", null);
        }
        String URLName = request.getScheme() + "://" + getNowIP2() + ":" + request.getServerPort() + "/" + "Activity/" + filename2;




        System.out.println(URLName);

        return activityService.insertActivity(URLName,Activity,pictureName,targetWeight);

    }


//    获取全部活动信息
    @GetMapping("/getAll")
    public Result getAll(){
        return activityService.getAll();
    }
    private static String getNowIP2() throws IOException {
        String ip = null;
        BufferedReader br = null;
        try {
            URL url = new URL("https://v6r.ipip.net/?format=callback");
            br = new BufferedReader(new InputStreamReader(url.openStream()));
            String s = "";
            StringBuffer sb = new StringBuffer("");
            String webContent = "";
            while ((s = br.readLine()) != null) {
                sb.append(s + "\r\n");
            }
            webContent = sb.toString();
            int start = webContent.indexOf("(") + 2;
            int end = webContent.indexOf(")") - 1;
            webContent = webContent.substring(start, end);
            ip = webContent;
        } finally {
            if (br != null)
                br.close();
        }
        if (StringUtils.isEmpty(ip)) {
            throw new RuntimeException();
        }
        return ip;
    }
}
